/*
 * This file is part of nettool4j.
 * 
 * rockframework is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * rockframework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>;.
 */
package net.woodstock.nettool4j.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.logging.Level;

import net.woodstock.nettool4j.AbstractRunnable;

public class UDPRedirect extends AbstractRunnable {

	private static final int	BUFF_SIZE	= 64;

	private int					listen;

	private String				host;

	private int					port;

	public UDPRedirect(final int listen, final String host, final int port) {
		super();
		this.listen = listen;
		this.host = host;
		this.port = port;
	}

	@Override
	public void run() {
		try {
			this.getLogger().log(Level.INFO, "Creating socket");
			DatagramSocket serverSocket = new DatagramSocket(this.listen);
			DatagramSocket clientSocket = new DatagramSocket();

			this.getLogger().log(Level.INFO, "Running " + SocketUtils.toString(serverSocket.getLocalSocketAddress()));

			while (this.isRunEnabled()) {
				DatagramPacket serverPacket = new DatagramPacket(new byte[UDPRedirect.BUFF_SIZE], UDPRedirect.BUFF_SIZE);
				serverSocket.receive(serverPacket);

				DatagramPacket clientPacket = new DatagramPacket(serverPacket.getData(), UDPRedirect.BUFF_SIZE, new InetSocketAddress(this.host, this.port));
				clientSocket.send(clientPacket);

			}
		} catch (IOException e) {
			this.getLogger().log(Level.WARNING, e.getMessage(), e);
		}
	}

}
